package io.adrainty.bolee.insurance.repository.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.adrainty.bolee.insurance.mapper.BannerMapper;
import io.adrainty.bolee.insurance.models.bo.BannerBO;
import io.adrainty.bolee.insurance.models.entity.BannerEntity;
import io.adrainty.bolee.insurance.repository.IBannerRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>BannerRepositoryImpl</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description IBannerRepository
 * @since 2025/8/18 16:10:55
 */

@Repository
public class BannerRepositoryImpl implements IBannerRepository {

    @Resource
    private BannerMapper bannerMapper;

    @Override
    public IPage<BannerEntity> pageBanner(Integer pageNum, Integer pageSize, BannerEntity param) {
        Page<BannerBO> page = new Page<>(pageNum, pageSize);
        Wrapper<BannerBO> wrapper = getWrapper(param);
        return bannerMapper.selectPage(page, wrapper).convert(item -> BeanUtil.toBean(item, BannerEntity.class));
    }

    @Override
    public Long saveBanner(BannerEntity bannerVO) {
        BannerBO bannerBO = BeanUtil.toBean(bannerVO, BannerBO.class);
        bannerMapper.insert(bannerBO);
        return bannerBO.getId();
    }

    @Override
    public void updateBannerById(BannerEntity bannerVO) {
        BannerBO bannerBO = BeanUtil.toBean(bannerVO, BannerBO.class);
        bannerMapper.updateById(bannerBO);
    }

    @Override
    public void deleteBatchBanner(List<Long> bannerIds) {
        bannerMapper.deleteByIds(bannerIds);
    }

    private Wrapper<BannerBO> getWrapper(BannerEntity param) {
        return Wrappers.lambdaQuery(BannerBO.class)
                .eq(StringUtils.isNotBlank(param.getBannerType()), BannerBO::getBannerType, param.getBannerType())
                .likeRight(StringUtils.isNotBlank(param.getUrl()), BannerBO::getUrl, param.getUrl())
                .orderByAsc(BannerBO::getSortNo)
                .orderByDesc(BannerBO::getCreatedTime);
    }

}
